/**
 * Created by jinxs on 14-6-25.
 */
(function ($) {
    /**
     * 缓存名称
     * @type {string}
     * @private
     */
    var _cacheName = 'uiDialog';

    /**
     * @class 对话框
     * @extends uiPanel
     * @requires {@link uiPanel}
     * @constructor uiDialog
     * @summary 构造函数
     * @param [options] {Object|String} 组件配置参数|要调用的组件方法名
     * @param [param] {Object} 表示要调用的组件方法的参数
     * @example
     * // 构件组件
     * $('#divDialog').uiDialog({title: '面板测试', width: 160, height: 500});
     * // 调用组件方法open
     * $('#divDialog').uiDialog("open");
     */
    $.fn.uiDialog = function (options, param) {
        if (typeof options == 'string') {
            return $.fn.uiDialog.methods[options](this, param);
        }
        return this.each(function(){
            var me = $(this);
            var cache = me.data(_cacheName);

            options = options || {};
            if (cache) {
                $.extend(cache.options, options);
            } else {
                me.data(_cacheName, {
                    options: $.extend({}, $.fn.uiDialog.defaults, $.fn.parseUIConfig(me, null), options)
                });
            }
            _init(me);
        });
    };

    $.fn.uiDialog.methods = $.extend({}, $.fn.uiPanel.methods,
        /**
         * 方法
         * @lends uiDialog.prototype
         */
        {
            /**
             * @summary 打开对话框
             * @name uiDialog#open
             * @function
             * @param [opts] {Object} 配置对象，具有属性forceOpen、horizontal、vertical,url
             * @returns {jQuery} 方法调用者
             */
            open: function (target, opts) {
                opts = opts || {};
                var options = $.data(target[0], _cacheName).options;
                var palOpts = target.uiPanel('options');
                var id = '#' + target.attr('id');
                palOpts = $.extend(palOpts, opts);
                if (palOpts.maximized) {
                    target.width(palOpts.width).height(palOpts.height);
                    setPos();
                    palOpts.left = parseInt(target.css('left'));
                    palOpts.top = parseInt(target.css('top'));
                    target.uiPanel('open', palOpts.forceOpen);
                    setPos();
                }
                else {
                    target.uiPanel('open', palOpts.forceOpen);
                    setPos();
                    palOpts.left = parseInt(target.css('left'));
                    palOpts.top = parseInt(target.css('top'));
                }
                function setPos() {
                    target.uiPosition({
                        horizontal: palOpts.horizontal == undefined ? 'center' : palOpts.horizontal,
                        vertical: palOpts.vertical == undefined ? 'center' : palOpts.vertical,
                        container: options.maskContainer,
                        fixed: false
                    });
                }

                return target;
            },
            /**
             * @summary 关闭对话框
             * @name uiDialog#close
             * @function
             * @param forceClose {Boolean} 是否强制关闭（忽略onBeforeClose事件返回的false）
             * @returns {jQuery} 方法调用者
             */
            close: function (target, forceClose) {
                var options = $.data(target[0], _cacheName).options;
                var id = '#' + target.attr('id');
                target.uiPanel('close', forceClose);
                return target;
            },
            /**
             * @summary 添加对话框按钮
             * @name uiDialog#buttonbar
             * @function
             * @param buttonConfig {Array<uiButton.options>} 按钮配置列表
             * @returns {jQuery} 方法调用者
             */
            buttonbar: function (target, buttonConfig) {
                _renderBtnbar(target, buttonConfig);
                return target;
            },
            /**
             * @summary 获取对话框按钮对象
             * @name uiDialog#button
             * @param buttonID {String} 按钮ID
             * @function
             * @returns {jQuery} 按钮
             */
            button: function (target, buttonID) {
                return $('#' + buttonID);
            },
            /**
             * TODO:
             * @summary setUserParam
             * @name uiDialog#setUserParam
             * @function
             * @returns {jQuery} 方法调用者
             */
            setUserParam: function (target, userparam) {
                return target.each(function(){
                    $.data(this, _cacheName).options.userParam = userparam;
                });
            },
            /**
             * TODO:
             * @summary getUserParam
             * @name uiDialog#getUserParam
             * @function
             * @returns {Object} 按钮
             */
            getUserParam: function (target, userparam) {
                var options = $.data(target[0], _cacheName).options;
                return options.userParam;
            }
        });

    $.fn.uiDialog.defaults = $.extend({}, $.fn.uiPanel.defaults,
        /**
         * 默认配置
         * @lends uiDialog.prototype
         */
        {
            /**
             * @type String
             * @default ui_panel
             * @summary 对话框面板样式
             */
            panelStyle: 'ui_panel',
            /**
             * @type Array
             * @default [15,15,15,15]
             * @summary 组件最大化时与父容器的间距(上、左、下、右)
             */
            maxPadding: [15, 15, 15, 15],
            /**
             * @type Boolean
             * @default true
             * @summary 对话框是否可拖动
             */
            draggable: true,
            /**
             * @type Boolean
             * @default true
             * @summary 对话框是否可改变大小
             */
            resizable: true,
            /**
             * @type Boolean
             * @default true
             * @summary 对话框是否可关闭
             */
            closable: true,
            /**
             * @type Boolean
             * @default true
             * @summary 对话框是否可最大化
             */
            maximizable: true,
            /**
             * @type Boolean
             * @default false
             * @summary 对话框是否包含遮罩
             */
            mask: false,
            /**
             * @type jQuery
             * @default $("body")
             * @summary 对话框遮罩范围对象
             */
            maskContainer: null,
            /**
             * @type Array<uiButton.options>
             * @default []
             * @summary 对话框按钮配置对象列表
             */
            buttons: []
            , zIndex: 888
        });
//////--------------------------------内部方法------------------------------
    /**
     * 创建按钮
     * @param target 目标对象
     */
    var _init = function (target) {
        var options = $.data(target[0], _cacheName).options;
        var content = target.children();//.detach(); // detach 后无法在uiPanel中显示
        var btnVisible = false;
        var btnLen = options.buttons.length;
        target.addClass('ui_dialog');
        if (options.maskContainer == null) {
            options.maskContainer = target.parent();
        }
        if (btnLen > 0) {
            btnVisible = true;
        }
        var id = '#' + target.attr('id');
        var maskID = target.getElemID() + '-dialog_mask';

        function showMask() {
            if (options.mask) {
                $.uiMask.show({
                    container: options.maskContainer,
                    maskID: maskID,
                    zIndex: options.zIndex - 1,
                    excludeSelector: id
                });
            }
        }

        function hideMask() {
            if (options.mask) {
                $.uiMask.hide({container: options.maskContainer, maskID: maskID, excludeSelector: id});
            }
        }

        target.uiPanel($.extend({}, options, {
            showBtnBar: btnVisible || options.showBtnBar,
            closed: true,
            content: content,
            onBeforeOpen: function () {
                options.onBeforeOpen.call(target);
                showMask();
            },
            onClose: function () {
                options.onClose.call(target);
                hideMask();
            }
        }));
        $(window).bind("resize", function () {
            if (target.attr('closed') == 'false') {
                target.uiPosition({horizontal: 'center', vertical: 'center', container: options.maskContainer});
            }
        });
        return target;
    };
})(jQuery);